package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.uitils.SMSUtils;
import com.itheima.uitils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValtdateCodeController {

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")//发送验证码
    public Result send4Order(String telephone){
         //验证手机号为空
        if(telephone != null){
            //生成验证码
               Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
              /* try {
                   //发送短信
                   SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
               } catch (ClientException e) {
                   e.printStackTrace();
                   //发送失败
                   return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
               }*/

               //成功发送,在Redis中存入验证码并规定有效时间，过期即删
               Jedis resource = jedisPool.getResource();
               resource.setex(telephone+RedisMessageConstant.SENDTYPE_ORDER,300,validateCode.toString());
               resource.setex(telephone,300,telephone);
               resource.close();
               return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
        //发送失败
        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
    }



    @RequestMapping("/send4Login")//发送验证码
    public Result send4Login(String telephone){
        //验证手机号为空
        if(telephone != null){
            //生成验证码
            Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
           /* try {
                //发送短信
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            } catch (ClientException e) {
                e.printStackTrace();
                //发送失败
                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            }
*/
            //成功发送,在Redis中存入验证码并规定有效时间，过期即删
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone+RedisMessageConstant.SENDTYPE_LOGIN,300,validateCode.toString());
            resource.setex(telephone+"login",300,telephone);
            resource.close();
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
        //发送失败
        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
    }

}
